package fr.bda.cloud.tray;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

/**
 * <PRE>
 * ---------------
 * | headPanel   |
 * ---------------
 * | formPanel   |
 * ---------------
 * | buttonPanel |
 * ---------------
 * </PRE>
 * 
 * @author BARET
 * 
 */
public abstract class CloudTrayDialog<C extends CloudTrayDialogController> extends JDialog {

	private static final long serialVersionUID = 1L;

	protected final C controller;
	protected final CloudTrayDialogListener listener;

	private final JPanel headPanel = new JPanel();
	private final JPanel formPanel = new JPanel();
	private final JPanel buttonPanel = new JPanel();
	private final JButton validButton = new JButton("OK");
	private final JButton cancelButton = new JButton("CANCEL");

	public CloudTrayDialog(final CloudTrayDialogListener listener, final C controller) {

		setTitle(this.getClass().getSimpleName());

		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		add(panel);

		panel.add(headPanel, BorderLayout.NORTH);
		panel.add(formPanel, BorderLayout.CENTER);
		panel.add(buttonPanel, BorderLayout.SOUTH);

		buttonPanel.add(validButton);
		buttonPanel.add(cancelButton);

		validButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (controller.checkDialogData(CloudTrayDialog.this)) {
					controller.saveDialogData(CloudTrayDialog.this);
					dispose();
					listener.onDialogValid(CloudTrayDialog.this);
				}
			}
		});

		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
				listener.onDialogCancel(CloudTrayDialog.this);
			}
		});

		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent evt) {
				dispose();
				listener.onDialogCancel(CloudTrayDialog.this);
			}
		});

		this.controller = controller;
		this.listener = listener;
		controller.initDialog(this);
		listener.onDialogInit(this);

		setModalityType(ModalityType.DOCUMENT_MODAL);
		setResizable(false);
		setLocationRelativeTo(null);
	}

	public JPanel getHeadPanel() {
		return headPanel;
	}

	public JPanel getFormPanel() {
		return formPanel;
	}

	public JPanel getButtonPanel() {
		return buttonPanel;
	}

	public JButton getValidButton() {
		return validButton;
	}

	public JButton getCancelButton() {
		return cancelButton;
	}

	public CloudTrayDialogController getController() {
		return controller;
	}

}
